<template>
  <!-- 左边表单 -->
  <div class="order_form">
    <!-- 乘机人数单 -->
    <div class="form_people">
      <h2>乘机人</h2>
      <!-- for -->
      <el-form ref="peopleArrayRef" :model="{peopleArray}">
        <div class="form_people_main" v-for="(item,index) of peopleArray" :key="index">
          <el-form-item :prop="`peopleArray[${index}].username`" :rules="[...peopleRule.username]">
            <p>乘机人</p>
            <el-input placeholder="姓名" v-model="item.username"></el-input>
          </el-form-item>

          <el-form-item :prop="`peopleArray[${index}].id`" :rules="[...peopleRule.id]">
            <p>证件类型</p>
            <el-input placeholder="证件号码" v-model="item.id" class="input-with-select certificate">
              <!-- slect value 1 默认选择第一个 -->
              <el-select slot="prefix" placeholder="身份证" value="1">
                <el-option label="身份证" value="1" :checked="true"></el-option>
                <el-option label="护照" value="2"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="el-icon-delete" v-show="index != 0" @click="deletePeople(index)"></span>
        </div>

        <!-- for -->
        <!-- 添加乘机人 -->
        <el-button type="primary" @click="addPeople">添加乘机人</el-button>
      </el-form>
    </div>
    <!-- 保险 -->
    <div class="insurance">
      <h2>保险</h2>
      <el-row>
        <el-checkbox-group v-model="insuranceList">
          <el-checkbox
            border
            v-for="(item,index) of orderData.insurances"
            :key="index"
            :label="item.id"
          >{{item.type+ ': ￥'+ item.price +'/份✖1 最高赔付'+item.compensation }}</el-checkbox>
        </el-checkbox-group>
      </el-row>
    </div>
    <!-- 联系人 -->
    <div class="contact">
      <h2>联系人</h2>

      <el-form label-width="80px" :model="contact" :rules="contactRule" ref="contactRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="contact.name"></el-input>
        </el-form-item>
        <el-form-item label="手机" class="mobile_phone" prop="phone">
          <el-input v-model="contact.phone"></el-input>
          <el-button type="info" @click="verificationCodeClick">获取验证码</el-button>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="contact.code"></el-input>
        </el-form-item>
      </el-form>
      <div class="sumbmit">
        <el-button type="warning" @click="submitForm">提交订单</el-button>
      </div>
    </div>
    <!-- 登录弹出框 -->
    <div class="loginTanchu" v-if="isShowLogin">
      <div class="login_title">
        <h2>闲云快速登录窗口</h2>
      </div>
      <el-form label-width="80px">
        <el-form-item label="用户名" v-model="userLogin.username">
          <el-input></el-input>
        </el-form-item>
        <el-form-item label="密码" v-model="userLogin.password">
          <el-input></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary">登录</el-button>
          <el-button @click="isShowLogin=false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
// https://blog.csdn.net/Thekingyu/article/details/103162944
// vue element validator 表单自定义组件验证精确身份证号码
import {checkIdNumberValid } from '@/plugins/util';
export default {
  props: ["orderData"],
  data() {
    const validatePassPeopleId = (rule, value, callback) => {
      let val  =checkIdNumberValid(value)
      if (val) {
        callback()
      }else{
        callback(new Error('身份证错误'))
      }
    }
    return {
      // 乘机人数组
      peopleArray: [
        {
          id: "",
          username: ""
        }
      ],
      // 保险
      insuranceList: [],
      // 联系人表单
      contact: {
        name: "",
        phone: "",
        code: ""
      },
      // 联系人表单验证
      contactRule: {
        name: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
          { min: 1, max: 10, message: "名字格式错误" }
        ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,message: '手机号格式不正确！', trigger: 'blur'}

        ],
        code: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          { min: 1, max: 10, message: "验证码错误" }
        ]
      },
      // 乘机人验证
      peopleRule: {
        username: [{ required: true, message: "请完善乘机人信息" }],
        id: [{ required: true, message: "请完善身份信息"},{  trigger: 'blur',validator: validatePassPeopleId}]
      },
      // 登录框
      isShowLogin: false,
      userLogin: {
        username: "",
        password: ""
      }
    };
  },
  watch: {
    peopleArray() {
      // console.log("乘机人数组");
      this.countMoney();
    },
    insuranceList() {
      this.countMoney();
      // console.log(this.insuranceList);
    }
  },
  methods: {
    // 添加 乘机人
    addPeople() {
      // console.log("添加");
      this.peopleArray.push({
        id: "",
        name: ""
      });
    },
    // 减少 乘机人
    deletePeople(index) {
      // 第一个不能删除
      if (index == 0) {
        return;
      }
      // 删除乘机人
      // this.peopleArray.splice(index,1);
      this.$delete(this.peopleArray, index);
    },
    // 获取验证码
    verificationCodeClick() {
      if (!this.contact.phone) {
        this.$message.error("手机号码不能为空");
        return;
      }
      
      // 无法单独判断 验证规则
      //  this.$refs.phoneRef.validate((valid)=>{
      //    if (valid) {
      //      console.log('正确');
           
      //    }else {
      //      console.log('错误');
      //    }
      //  });
      // 正则判断手机号码是否正确
      const PhoneRegExp = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (!PhoneRegExp.test(this.contact.phone)) {
            this.$message.error("手机号码格式错误");
        return;
      }

      this.$axios({
        method: "post",
        url: "/captchas",
        data: {
          tel: this.contact.phone
        }
      }).then(res => {
        // console.log('验证码',res);
        const { code } = res.data;
        this.$message.success("获取验证码成功");
        setTimeout(() => {
          this.contact.code = code;
        }, 1000);
      });
    },
    // 提交订单
    submitForm() {
      if (!this.$store.state.user.userInfo.token) {
        console.log("没有登录,请你登录");
        const h = this.$createElement;
        this.$notify({
          title: "温馨提示:你还没登录",
          message: h("i", { style: "color: teal" }, "点击此处 快速登录!!"),
          onClick: () => {
            this.isShowLogin = true;
          }
        });

        return false;
      }

      const contactRef = this.$refs.contactRef.validate();
      const peopleArrayRef = this.$refs.peopleArrayRef.validate();
      // const peopleArrayRefArray = this.$refs.peopleArrayRef.map(item => {
      //   return item.validate();
      // });

      Promise.all([contactRef, peopleArrayRef])
        .then(res => {
          // console.log('res: ', res);
          // 全部为真才是真
          let valid = res.every(item => {
            return item;
          });
          //  console.log('valid: ', valid);

          if (valid) {
            this.$message.success("请稍等");
            const data = {
              users: this.peopleArray,
              insurances: this.insuranceList,
              contactName: this.contact.name,
              contactPhone: this.contact.phone,
              captcha: this.contact.code,
              // 是否需要发票
              invoice: false,
              seat_xid: this.$route.query.seat_xid,
              air: this.$route.query.id
            };
            // console.log('data: ', data);
            this.$axios({
              url: "/airorders",
              method: "post",
              data,
              // 需要添加 token 使用 JWT 的格式 ( token 指的是一串字符串, JWT 指的是如何生成和使用这个字符串的标准)
              // 遇到按照文档发送请求, 对照过数据没有问题的情况, 工作当中可以问后端, 项目当中可以参考成型的示例网站, 我们的提交订单接口文档中少了一个 手机验证码的参数要加上去
              headers: {
                Authorization: "Bearer " + this.$store.state.user.userInfo.token
              }
            }).then(res => {
             const {data} = res.data
             console.log('data: ', data);
              this.$message.success(res.data.message);
              this.$router.push({
                path:"/air/pay",
                query: {
                  id:data.id
                }
              })
            });
          }
          //   // this.$axios({
          //   //   url: "/airorders",
          //   //   method: "post",
          //   //   data,
          //   //   headers: {
          //   //     // token 遗传校验字符串,
          //   //     // 如何带 token 的标准方式, 有一个标准叫做 JWT
          //   //     Authorization: "Bearer " + this.$store.state.user.userInfo.token
          //   //   }
          //   // }).then(res => {
          //   //   console.log(res.data);
          //   // });
          // }
          //  else {
          //   console.log("失败");
          //   this.$message.error("提交失败 请正确输入信息");
          //   return false;
          // }
        })
        .catch(err => {
          this.$message.error("提交失败 请正确输入信息");
          return false;
          //  console.log('err: ', err);
        });
    },
    // 计算总额
    countMoney() {
      let money = 0;
      // 人数
      const peopleTotal = this.peopleArray.length;
      // 机票价格
      money += this.orderData.base_price;
      // 过滤出已选中的保险
      this.orderData.insurances.forEach(item => {
        if (this.insuranceList.indexOf(item.id) > -1) {
          money += +item.price;
        }
      });
      money = money * peopleTotal;
      this.$emit("moneyTotal", money);
    }
  },
  mounted() {
    // console.log(this.orderData);
    this.countMoney();
  },
  destroyed() {
    console.log("销毁完毕");
  }
};
</script>

<style lang="less" scoped>
/deep/ .is-success {
  /deep/ .el-input__inner {
    // outline: green;
    border: 1px solid green;
  }
}
.order_form {
  width: 590px;
  h2 {
    font-size: 22px;
    font-weight: 400;
    margin: 20px 0;
  }
  // 乘机人表单
  .form_people {
    padding-bottom: 20px;
    border-bottom: 1px dashed #dcdfe6;
    //   添加乘机人按钮
    /deep/ .el-button--primary {
      margin-top: 40px;
    }
    // 循环的people
    .form_people_main {
      padding-bottom: 20px;
      border-bottom: 1px dashed #dcdfe6;
      position: relative;
      p {
        padding: 12px 0;
        font-size: 14px;
      }
      // 删除按钮
      .el-icon-delete {
        position: absolute;
        right: 0;
        top: 10px;
        cursor: pointer;
      }
      //  el-select
      /deep/ .el-input__prefix {
        left: 0;
        width: 130px;
      }
      /deep/ .el-input > input {
        padding-left: 15px;
      }
      // 取消蓝色
      /deep/ .el-select .el-input.is-focus .el-input__inner {
        border-color: #ced1d9;
      }
      /deep/ .el-select .el-input__inner:focus {
        border-color: #ced1d9;
      }
      /deep/ .el-input.is-active .el-input__inner,
      .el-input__inner:focus {
        border-color: #ced1d9;
      }
      /deep/ .el-input.is-active .el-input__inner,
      .el-input__inner:focus {
        border-color: #ced1d9;
      }
      // 证件类型 缩进
      /deep/ .certificate > input {
        text-indent: 130px;
      }
    }
  }
  // 保险
  .insurance {
    padding-bottom: 20px;
    border-bottom: 1px dashed #dcdfe6;
    /deep/ .el-checkbox {
      margin: 10px 0;
    }
  }
  // 联系分
  .contact {
    /deep/ .el-form-item__label {
      &:before {
        content: "*";
        padding-right: 5px;
        color: orange;
      }
    }
    /deep/ .el-input {
      width: 250px;
    }
    // 手机
    .mobile_phone {
      /deep/ .el-form-item__content {
        display: flex;
        align-items: center;
        /deep/ .el-input {
          width: 142px;
          display: flex;
          align-items: center;
          /deep/ .el-input__inner {
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
          }
        }
        /deep/ .el-button {
          // transform: translateY(1px);
          background: #f5f7fa;
          color: #909399;
          width: 112px;
          border-color: #dcdfe6;
          border-top-left-radius: 0;
          border-bottom-left-radius: 0;
        }
      }
    }
    .sumbmit {
      height: 160px;
      position: relative;
      /deep/ .el-button {
        width: 250px;
        height: 50px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
  }
}
// 登录弹出
.loginTanchu {
  position: fixed;
  z-index: 100;
  top: 100px;
  left: 50%;
  transform: translateX(-50%);
  width: 550px;
  height: 330px;
  border: 1px solid #ccc;
  background: white;
  .login_title {
    text-align: center;
    padding: 30px 0;
    h2 {
      font-size: 30px;
    }
  }
  /deep/ .el-form {
    margin: auto;
    transform: translateX(-15%);
    width: 400px;
  }
}
</style>